<template>
    <n-form ref="formRef" :model="formValue" label-placement="left" :rules="rules" :label-width="80">
        <n-form-item label="原密码" path="oldPwd">
            <n-input type="password" v-model:value="formValue.oldPwd" show-password-on="click" placeholder="请输入原密码" />
        </n-form-item>
        <n-form-item label="新密码" path="newPwd">
            <n-input
                type="password"
                v-model:value="formValue.newPwd"
                @input="handleNewPwdChange"
                show-password-on="click"
                placeholder="请输入新密码"
            />
        </n-form-item>
        <n-form-item label="确认密码" path="newPwdRepeat" ref="newPwdRepeatRef">
            <n-input type="password" v-model:value="formValue.newPwdRepeat" show-password-on="click" placeholder="请输再次输入新密码" />
        </n-form-item>
        <n-form-item>
            <n-space :style="{ marginLeft: '80px' }">
                <n-button attr-type="button" type="primary" @click="handleSubmit"> 确定 </n-button>
            </n-space>
        </n-form-item>
    </n-form>
</template>

<script setup lang="ts">
import { api } from "@/api/ucenter"
import { FormInst, FormRules } from "naive-ui"

const formRef = ref<FormInst | null>(null)
const formValue = ref<Recordable>({})
const newPwdRepeatRef = ref()

const handleNewPwdChange = () => {
    if (formValue.value.newPwdRepeat) {
        newPwdRepeatRef.value?.validate({ trigger: "password-input" })
    }
}

const rules: FormRules = {
    oldPwd: [{ required: true, message: "请输入原密码" }],
    newPwd: [{ required: true, message: "请输入新密码" }],
    newPwdRepeat: [
        {
            required: true,
            message: "请再次输入新密码",
            trigger: ["input", "blur"]
        },
        {
            validator: (_rule, value) =>
                !!formValue.value.newPwd && formValue.value.newPwd.startsWith(value) && formValue.value.newPwd.length >= value.length,
            message: "两次密码输入不一致",
            trigger: "input"
        },
        {
            validator: (_rule, value) => value === formValue.value.newPwd,
            message: "两次密码输入不一致",
            trigger: ["blur", "password-input"]
        }
    ]
}

const handleSubmit = () => {
    formRef.value
        ?.validate(async errors => {
            if (!errors) {
                const params = {
                    oldPwd: formValue.value.oldPwd,
                    newPwd: formValue.value.newPwd,
                    newPwdRepeat: formValue.value.newPwdRepeat
                }
                await api.updatePassword(params)
            }
        })
        .catch(() => {})
}
</script>
